package a66weding.com.jiehuntong.activity.order;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.HashMap;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.home.adapter.OrderDetailsAdapter;
import a66weding.com.jiehuntong.activity.me.MeBaseActivity;
import a66weding.com.jiehuntong.activity.me.MePayActivity;
import a66weding.com.jiehuntong.activity.me.MeShoppingCartActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MyOrderBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.WxremindBean;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.StrUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.widgets.MyListView;

/**
 * Created by admin on 2016/8/31.
 * 订单详情;
 * get_MyOrderDetail
 * orderState=6, orderStateStr='已完成'
 */
public class OrderDetailsActivity extends MeBaseActivity implements OnNetResultListener, View.OnClickListener {
    private TextView title_tv;
    private MyOrderBean.DataBean orderDataBean;
    //收件人
    private TextView order_shojianren;
    //电话
    private TextView order_dianhua;
    //地址
    private TextView order_sjrd_tv;
    //订单编号
    private TextView acty_ordernumber_tv;
    //支付方式
    private TextView acty_orderpayway_tv;
    //确认收货
    private TextView orderdetail_shouhuo_tv;
    //订单的状态显示的内容;
    private TextView order_state;
    //订单的状态
    private TextView orderDetail;
    //底部的得整体布局;
    private RelativeLayout acty_order_bottemg;
    //配送方式
    private TextView order_peisonway;
    //是否开发票
    private TextView order_isfapiao_tv;
    //公司名字
    private TextView order_detail_tv;
    //提交订单的时间
    private TextView act_submitorder_tv, act_submitorder_tv1;
    //支付时间
    private TextView acty_paymenttime_tv, acty_paymenttime_tv1;
    //完成时间
    private TextView order_sure_tv, order_sure_tv1;
    //状态2
    private ImageView iv_fourthly2;
    private ImageView iv_fourthly3;
    //晒订单
    private TextView pingjiashaidan_tv;
    //空间
    private LinearLayout oderspace;
    //打电话
    private LinearLayout mToCallLay;
    private PopupWindow mPopWindow;
    //订单详情的付款时间
    private TextView order_paytime_tv;
    //留言;
    private TextView nvc_Remarks;
    private TextView mTuihuanTv;//退货
    //退后
    private TextView oder_tuihuo;
    //订单状态
    private int state;
    //订单类型
    private TextView order_isfapiao_FPType;
    //适配器
    private OrderDetailsAdapter orderDetailsAdapter;
    //list
    private MyListView order_list;
    // 向购物车添加商品的bean
    private CommonResultBean commonResultBean;
    // 统计网络请求的次数
    private int count = 0;
    ArrayList<MyOrderBean.DataBean.MyOrderDetailBean> myOrderList;
    // 付款
    private TextView mPayTv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orderdetails);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("OrderDetailsActivity", this);
        tuihuanActivityMap.put("OrderDetailsActivity",this);
        EventBus.getDefault().register(this);
        orderDataBean = (MyOrderBean.DataBean) getIntent().getSerializableExtra("orderDataBean");
        initView();
        initData();
    }

    /**
     * 界面显示调用的方法
     */
    @Override
    protected void onResume() {
        super.onResume();
        // 界面显示把count置空
        count = 0;
    }

    private void initView() {
        order_isfapiao_FPType = (TextView) findViewById(R.id.order_isfapiao_FPType);
        state =  orderDataBean.getOrderState();
        oder_tuihuo = (TextView) findViewById(R.id.oder_tuihuo);
        nvc_Remarks = (TextView) findViewById(R.id.order_nvc_Remarks_tv);
        order_paytime_tv = (TextView) findViewById(R.id.order_paytime_tv);
        oderspace = (LinearLayout) findViewById(R.id.oderspace);
        pingjiashaidan_tv = (TextView) findViewById(R.id.pingjiashaidan_tv);
        pingjiashaidan_tv.setOnClickListener(this);
        iv_fourthly3 = (ImageView) findViewById(R.id.iv_fourthly3);
        iv_fourthly2 = (ImageView) findViewById(R.id.iv_fourthly2);
        order_sure_tv = (TextView) findViewById(R.id.order_sure_tv);
        order_sure_tv1 = (TextView) findViewById(R.id.order_sure_tv1);
        acty_paymenttime_tv1 = (TextView) findViewById(R.id.acty_paymenttime_tv1);
        act_submitorder_tv1 = (TextView) findViewById(R.id.act_submitorder_tv1);
        order_detail_tv = (TextView) findViewById(R.id.order_detail_tv);
        order_isfapiao_tv = (TextView) findViewById(R.id.order_isfapiao_tv);
        order_peisonway = (TextView) findViewById(R.id.order_peisonway);
        acty_order_bottemg = (RelativeLayout) findViewById(R.id.acty_order_bottemg);
        order_state = (TextView) findViewById(R.id.order_state);
        orderdetail_shouhuo_tv = (TextView) findViewById(R.id.orderdetail_shouhuo_tv);
        orderdetail_shouhuo_tv.setOnClickListener(this);
        order_sjrd_tv = (TextView) findViewById(R.id.order_sjrd_tv);
        order_dianhua = (TextView) findViewById(R.id.order_dianhua);
        acty_paymenttime_tv = (TextView) findViewById(R.id.acty_paymenttime_tv);
        orderDetail = (TextView) findViewById(R.id.orderDetail);
        title_tv = (TextView) findViewById(R.id.title_tv);
        act_submitorder_tv = (TextView) findViewById(R.id.act_submitorder_tv);
        order_shojianren = (TextView) findViewById(R.id.order_shojianren);
        acty_ordernumber_tv = (TextView) findViewById(R.id.acty_ordernumber_tv);
        acty_orderpayway_tv = (TextView) findViewById(R.id.acty_orderpayway_tv);
        mPayTv = (TextView) findViewById(R.id.order_state_pay);
        mTuihuanTv = (TextView) findViewById(R.id.oder_tuihuo);
        mToCallLay = (LinearLayout) findViewById(R.id.lay_oederdetaild_callPhone);
        title_tv.setText("订单详情");
        order_list = (MyListView) findViewById(R.id.order_list);
        orderDetailsAdapter = new OrderDetailsAdapter(this,orderDataBean);
        order_list.setAdapter(orderDetailsAdapter);
        mToCallLay.setOnClickListener(this);
        mTuihuanTv.setOnClickListener(this);
        mPayTv.setOnClickListener(this);
    }

    private void initData() {
        if (orderDataBean != null) {
            orderDetail.setText(orderDataBean.getOrderStateStr());
            switch (orderDataBean.getOrderState()){
                case 1://待审核
                    order_state.setText("您的订单已提交,请");
                    mPayTv.setVisibility(View.VISIBLE);
                    mPayTv.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG); //下划线
                    mPayTv.getPaint().setAntiAlias(true);//抗锯齿
                    hide();
                    break;
                case 3://待确认
                    order_state.setText("您已付款成功,我们正在为您发货");
                    hide();
                    break;
                case 4://待发货
                    order_state.setText("您已付款成功,我们正在为您发货");
                    hide();
                    break;
                case 5://已发货
                    order_state.setText("已经发货");
                    Shipped();
                    break;
                case 6://已完成;
                    if (orderDataBean.getMyOrderDetail().get(0).getI_OrderComment()==1){
                        //已经评论了
                        order_state.setText("订单已完成!");
                        changeHide();
                    }else{
                        order_state.setText("订单已完成,快来评价吧");
                    }
                    break;
                case 7://已取消
                    hide();
                    break;
            }
            switch (orderDataBean.getOrderStateStr()) {
                default:
                    break;
            }
        }
        //提交订单;时间;
        if (!TextUtils.isEmpty(orderDataBean.getOrderSubmitDatetime())) {
            String[] time = Tools.getStringArray(orderDataBean.getOrderSubmitDatetime());
            act_submitorder_tv.setText(time[0]);
            act_submitorder_tv1.setText(time[1]);
        }
        //付款时间
        if (!TextUtils.isEmpty((String) orderDataBean.getOrderPayDatetime())) {
            String[] time = Tools.getStringArray((String) orderDataBean.getOrderPayDatetime());
            acty_paymenttime_tv.setText(time[0]);
            acty_paymenttime_tv1.setText(time[1]);
            //订单信息中的付款时间
            order_paytime_tv.setText(time[0]+" "+time[1]);
        } else {
            iv_fourthly2.setImageResource(R.mipmap.oder_wu);
        }

        if (orderDataBean.getOrderState()==6){
            if (orderDataBean.getOrderSureDatetime()!=null){
                String[] time = Tools.getStringArray((String) orderDataBean.getOrderSureDatetime());
                order_sure_tv.setText(time[0]);
                order_sure_tv1.setText(time[1]);
            }
            orderdetail_shouhuo_tv.setText("再次购买");
        }else{
            iv_fourthly3.setImageResource(R.mipmap.oder_wu);
        }
        if (orderDataBean.getOrderState()==5){
            orderdetail_shouhuo_tv.setText("确定收货");
        }

        //收件人;
        if (!TextUtils.isEmpty(orderDataBean.getConsigneeName())) {
            order_shojianren.setText(orderDataBean.getConsigneeName());
        } else {
            order_shojianren.setText("");
        }
        //电话
        if (!TextUtils.isEmpty(orderDataBean.getConsigneeMobilePhone())) {
            order_dianhua.setText(orderDataBean.getConsigneeMobilePhone());
        } else {
            order_dianhua.setText(" ");
        }
        //收件人地址POST WeddingMobileApi/post_SureGoodsReceipt?Token={Token}&ids={ids}
        if (!TextUtils.isEmpty(orderDataBean.getConsigneeAddress())) {
            order_sjrd_tv.setText("地址:" + orderDataBean.getConsigneeAddress());
        }
        //订单编号
        if (!TextUtils.isEmpty(orderDataBean.getOrdersNumber())) {
            acty_ordernumber_tv.setText(orderDataBean.getOrdersNumber());
        }
        //支付方式
        if (!TextUtils.isEmpty(orderDataBean.getPayStyle())) {
            acty_orderpayway_tv.setText(orderDataBean.getPayStyle());
        }
        //快递方式;
        if (!TextUtils.isEmpty(orderDataBean.getPsWay())) {
            order_peisonway.setText(orderDataBean.getPsWay());
        }
        //产品数量
        int num = orderDataBean.getMyOrderDetail().get(0).getBuyNumber();
        //产品单价
        Double sigleprice = orderDataBean.getMyOrderDetail().get(0).getSinglePrice();
        //产品运费
        Double ps = orderDataBean.getMyOrderDetail().get(0).getDm_CouponMoney();
        //总共金额
        Double total = (sigleprice * num) + ps;
        switch (orderDataBean.getFPInfo()) {
                case 0:
                    order_isfapiao_tv.setText("不开发票");
                break;
                 case 1:
                     order_isfapiao_tv.setText("普通发票");
                break;
                case 2:
                    order_isfapiao_tv.setText("增值发票");
                    break;

        }

        if (!TextUtils.isEmpty((String)orderDataBean.getFPTitle())){
            order_isfapiao_FPType.setText(""+orderDataBean.getFPTitle());
        }else{
            order_isfapiao_FPType.setText("- -");
        }

        //公司名字
        order_detail_tv.setText(orderDataBean.getBusinessName());
        //订单id
        ids = ""+orderDataBean.getOrdersID();
        //留言
        if (!TextUtils.isEmpty(orderDataBean.getNvc_Remarks())){
           nvc_Remarks.setText(orderDataBean.getNvc_Remarks());
        }
    }
    public void back(View view) {
        finish();
    }
    //隐藏
    private void hide() {
        acty_order_bottemg.setVisibility(View.GONE);
        oderspace.setVisibility(View.GONE);
    }
    //收货
    private WxremindBean wxremindBean;

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof WxremindBean) {
            wxremindBean = (WxremindBean) data;
            //确定收货;
            if (wxremindBean.isResult()) {
                CUtils.showToast(wxremindBean.getMsg());
                finish();
            }
        }
        if (data instanceof CommonResultBean) {
            commonResultBean = (CommonResultBean) data;
            if ("0000".equals(commonResultBean.getResCode())){
                count++;
                if (count == myOrderList.size()){
                    // 跳到购物车界面
                    Intent intent = new Intent(OrderDetailsActivity.this, MeShoppingCartActivity.class);
                    startActivity(intent);
                }
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {
    }

    //已发货修改状态
    private void Shipped(){
        oder_tuihuo.setVisibility(View.INVISIBLE);
        pingjiashaidan_tv.setText("查看物流");
    }

    //已评论后的订单进行操作
    private void changeHide(){
        pingjiashaidan_tv.setVisibility(View.GONE);
    }

    //确定收货地址;
    /**
     * POST WeddingMobileApi/post_SureGoodsReceipt?Token={Token}&ids={ids}
     * 确认收货
     */
    //订单号
    private String ids;
    private void ok_receipt() {
        String url = Url.POST_SUREGOODSRECEIPT + "ids=" + ids;
        HashMap<String,String> paramsMap=new HashMap<>();
        int id = DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        String nvc_name = DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_Name();
        paramsMap.put("i_Id",""+id);
        paramsMap.put("nvc_Name",nvc_name);
        HttpRequestBean httpRequestBean =
                new HttpRequestBean(RequestCode.POSTEQUEST, url, this, WxremindBean.class, RequestCode.ADDTYPEWEDDINGPROCESS,paramsMap);
        HttpHandleUtil.executeCommonPost(this, httpRequestBean);
    }


    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.orderdetail_shouhuo_tv:
                switch (orderDataBean.getOrderState()){
                    case 5:
                        //确认收货
                        ok_receipt();
                        break;
                    case  6:
                        //再次购买
                        int productId;
                        String url=RequestCode.AddShops;
                        myOrderList = (ArrayList<MyOrderBean.DataBean.MyOrderDetailBean>) orderDataBean.getMyOrderDetail();
                        for (int i = 0; i<myOrderList.size(); i++){
                            productId = myOrderList.get(i).getProductID();
                            url += "&memberID="+DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id()
                                +"&number="+1+"&productID="+productId;
                            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                                this, CommonResultBean.class, RequestCode.AddShops);
                            HttpHandleUtil.executeCommonPost(this,httpRequestBean);
                        }
                        break;
                    default:
                        break;
                }

                break;

            case R.id.pingjiashaidan_tv://评价晒单;
                if (state==5){
                    intent.setClass(this,LogisticsActivity.class);
                    int ordersID = orderDataBean.getOrdersID();
                    intent.putExtra("ordersID",ordersID);
                    startActivity(intent);
                }else{
                    intent.setClass(this,EvaluationActivity.class);
                    intent.putExtra("orderDataBean", orderDataBean);
                    startActivity(intent);
                }

                break;

            case R.id.lay_oederdetaild_callPhone://打电话
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                    mPopWindow = null;
                }
                showPopupWindow();
                break;
            case R.id.oder_tuihuo://退货
                Intent intent2 = new Intent(this, ApplyServicePreFirstActivity.class);
                intent2.putExtra("orderDataBean",orderDataBean);
                startActivity(intent2);

                break;
            case R.id.order_state_pay://付款

                //跳到支付界面
                String ordersNumber = orderDataBean.getOrdersNumber();
                float groupMoney = orderDataBean.getGroupMoney();
                double payMoney = orderDataBean.getDm_PSMoney() + groupMoney;
                float newPayMoney = StrUtil.floatNumDeal((float) payMoney);
                Intent intent3 = new Intent(this, MePayActivity.class);
                intent3.putExtra("isFromMyOrder", true);
                intent3.putExtra("ordersNumber", ordersNumber);
                intent3.putExtra("newPayMoney", newPayMoney);
                startActivity(intent3);

                break;
        }
    }


    //显示窗体
    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(OrderDetailsActivity.this).inflate(R.layout.pop_home_wedreg_phone, null);
        mPopWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT, true);
        //设置各个控件的点击响应
        RelativeLayout mPhoneRaly = (RelativeLayout) contentView.findViewById(R.id.rlay_phonenum);
        RelativeLayout mCallRaly = (RelativeLayout) contentView.findViewById(R.id.rl_home_call);
        TextView mCancelTv = (TextView) contentView.findViewById(R.id.tv_telephone_cancel);
        TextView mCallPhonelTv = (TextView) contentView.findViewById(R.id.tv_firstnum);
        TextView mCallTv = (TextView) contentView.findViewById(R.id.tv_home_call);
        mCallRaly.setVisibility(View.GONE);
        String businessTelPhone="";
        String businessMobilePhone="";
        if (orderDataBean != null) {
            businessTelPhone = orderDataBean.getBusinessTelPhone();
            businessMobilePhone= orderDataBean.getBusinessMobilePhone();
            if (TextUtils.isEmpty(businessMobilePhone) ) {
                mCallRaly.setVisibility(View.GONE);
            } else {
                mCallRaly.setVisibility(View.VISIBLE);
                mCallTv.setText(businessTelPhone);
            }
            mCallPhonelTv.setText(businessMobilePhone);
            mCallRaly.setOnClickListener(new View.OnClickListener() {  // 点击电话按钮
                @Override
                public void onClick(View v) {
                    String call = orderDataBean.getBusinessTelPhone();
                    Uri uri = Uri.parse("tel:" + call);
                    Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                    startActivity(intent);
                }
            });
            mPhoneRaly.setOnClickListener(new View.OnClickListener() {  // 点击手机按钮
                @Override
                public void onClick(View v) {
                    String phone = orderDataBean.getBusinessMobilePhone();
                    Uri uri = Uri.parse("tel:" + phone);
                    Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                    startActivity(intent);
                }
            });
            mCancelTv.setOnClickListener(new View.OnClickListener() {   //点击取消按钮
                @Override
                public void onClick(View v) {
                    if (mPopWindow != null) {
                        mPopWindow.dismiss();
                        mPopWindow = null;
                    }
                }
            });
        }
        mPopWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int eventY = (int) event.getY();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (eventY < 700) {
                            mPopWindow.dismiss();
                            return true;
                        }
                        break;
                }
                return false;
            }
        });

        mPopWindow.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(getResources().getColor(R.color.whitetranslucenthalf2));
        mPopWindow.setBackgroundDrawable(dw);
        // 设置popWindow的显示和消失动画
        mPopWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        // 在底部显示
        mPopWindow.showAtLocation(mToCallLay, Gravity.BOTTOM, 0, 0);
//        mPopWindow.showAsDropDown(mBackLay);
    }

    @Subscribe
    public void onEventMainThread(MessageEvent event) {
      if (event.getWhichisPinlun()!=-1){
          //评价成功了
          pingjiashaidan_tv.setVisibility(View.GONE);
      }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
